<template>

  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>礼品管理</el-breadcrumb-item>
      <el-breadcrumb-item>礼品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>

      <el-form :inline="true" :model="queryinfo" class="demo-form-inline" size="mini">
        <el-form-item label="礼品名称">
          <el-input v-model="queryinfo.name" placeholder="礼品名称" clearable/>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryinfo.statu" placeholder="状态" clearable filterable>
            <el-option label="上线" value="1"></el-option>
            <el-option label="下线" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="GetData">查询</el-button>
          <el-button type="primary" @click="drawer=true;drawerTitle=1;form={}">添加礼品</el-button>
        </el-form-item>
      </el-form>

      <hr>
      <el-table :data="tableData" style="width: 100%; ">
        <el-table-column prop="id" label="礼品ID" width="180"/>
        <el-table-column prop="name" label="礼品名称" width="180"/>
        <el-table-column prop="num" label="礼品数量" width="180"/>
        <el-table-column prop="quota" label="兑换积分" width="180"/>
        <el-table-column prop="statu" label="礼品状态" width="180">
          <template #default="props">
            <el-tag type="success" v-if="props.row.statu === 1" size="mini">上架</el-tag>
            <el-tag type="info" v-else size="mini">下架</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="#操作" width="180">
          <template #default="props">
            <el-button size="mini" type="primary" @click="drawer=true;drawerTitle=2;form=props.row">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <br>
      <!--分页-->
      <el-pagination
          background
          :current-page="queryinfo.page"
          :page-sizes="[3,10, 50, 100, 1000]"
          :page-size="queryinfo.size"
          layout="total, sizes, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="changePage"
      />
    </el-card>

    <el-drawer
        v-model="drawer"
        :title="drawerTitle===1?'添加礼品':'修改礼品'"
        direction="rtl"
    >
      <el-form :model="form" label-width="120px">
        <el-form-item label="礼品名称">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="积分">
          <el-input-number v-model="form.quota"></el-input-number>
        </el-form-item>
        <el-form-item label="礼品数量">
          <el-input-number v-model="form.num"></el-input-number>
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
              class="avatar-uploader"
              :auto-upload="false"
              action="#"
              :show-file-list="false"
              :on-change="OnHandleChange"
          >
            <img v-if="form.img" :src="form.img" class="avatar"/>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="礼品状态">
          <el-switch
              v-model="form.statu"
              :active-value=1
              :inactive-value=2
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onSubmit">{{ drawerTitle === 1 ? "Create" : "Update" }}</el-button>
          <el-button @click="drawer=false;form={}">Cancel</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>

  </div>
</template>

<script>
import {onMounted, reactive, toRefs} from 'vue'
import axios from '@/utils/axios'
import ObsClient from 'esdk-obs-browserjs'

var obsClient
import {formatTimeToStr} from '@/utils/date'
import {ElMessage,ElLoading } from 'element-plus'

export default {
  name: 'Good',
  setup() {
    const state = reactive({
      loading:false,
      queryinfo: {
        page: 1,
        size: 10
      },
      currentPage: 1, // 当前页
      pageSize: 10, // 分页大小
      total: 0,
      tableData: [],

      //抽屉编辑
      form: {},
      drawer: false,
      drawerTitle: 1
    })
    onMounted(() => {
      GetData()
      obsClient = new ObsClient({
        access_key_id: "7MHNBAYEIXMXXR0NSEMV",
        secret_access_key: "C3DKdIgRuWOAZfj0CN6QKmRTPtcdNaMVRFFVDlpe",
        server: "obs.cn-south-1.myhuaweicloud.com",
        timeout: 60 * 5,
      });

    })
    const onSubmit = async () => {
      if (state.drawerTitle === 1) {
        const {data: res} = await axios.put('gift', state.form)
        if (res.code !== 1000) return ElMessage.error(res.msg)
      } else {
        const {data: res} = await axios.post('gift', state.form)
        if (res.code !== 1000) return ElMessage.error(res.msg)
      }
      ElMessage.success("成功")
      state.drawer = false
      GetData()
    }
    // 获取轮播图列表
    const GetData = async () => {
      const {data: res} = await axios.get('gift', {params: state.queryinfo})
      if (res.code !== 1000) return ElMessage.error(res.msg)
      state.tableData = res.data.list
      state.total = res.data.total
    }
    const changePage = (val) => {
      console.log(11)
      state.queryinfo.page = val
      GetData()
    }

    const handleSizeChange = (val) => {
      state.queryinfo.size = val
      GetData()
    }

    const formatDate = (time) => {
      if (time !== null && time !== '') {
        var date = new Date(time)
        return formatTimeToStr(date, 'yyyy-MM-dd hh:mm:ss')
      } else {
        return ''
      }
    }

    const OnHandleChange = (file) => {
     let loading = ElLoading.service({
        lock: true,
        text: '上传中....',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      const isJPG = file.raw.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        loading.close()
        ElMessage.error('Avatar picture must be JPG format!')
        return
      }
      if (!isLt2M) {
        loading.close()
        ElMessage.error('Avatar picture size can not exceed 2MB!')
        return
      }

      let imgName = `guess/${file.name}`;
      obsClient.putObject({
        Bucket: "meimei",
        Key: imgName, //随机十位数字符串,
        Metadata: {property: "property-value"},
        SourceFile: file.raw,
        ContentType: 'text/plain',
      }).then(() => {
        loading.close()
        state.form.img = `https://img.feetbook.cn/${imgName}`;
        ElMessage.success("上传完毕")
      }).catch(function (err) {
        loading.close()
        ElMessage.error(err)
      });
    }
    return {
      ...toRefs(state),
      GetData,
      changePage,
      formatDate,
      handleSizeChange,
      onSubmit,
      OnHandleChange
    }
  }
}

</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
